Rubyは、厳格なシグネチャから 動的インターフェースへと進化させます。そして、 スプラット オペレータと式ベースの論理を習得することで、複雑なオーバーロードなしに、データ密度の変化に柔軟に対応するメソッドを構築できます。
1. 智能的なデフォルト値とスプラット
Rubyでは、パラメータをシグネチャ内で初期化できるため、データが少なくても機能を確保できます。 スプラット演算子(*) これは橋渡しの役割を果たします。パラメータでは、追加の引数を配列に収集し、呼び出しでは配列を個別の引数に展開します。
2. 式に基づく戻り値
Rubyのメソッドは、自動的に 最後に実行された式の値を返します。ただし、 return キーワードは、早期リターンや並列代入用に複数の値を配列として返すために意図的に使用されます。 並列代入。
num, sq = meth_three
# Rubyは (num, sq) を配列 [32, 1024] としてパッケージします
# Rubyは (num, sq) を配列 [32, 1024] としてパッケージします
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What is the primary role of the asterisk (*) in a method parameter list?
To mark a variable as a pointer to a memory address.
To capture a variable number of arguments into a single array.
To multiply the incoming argument by its index.
To indicate the method is private.
✅ Correct!
In a signature, `*` bundles all 'extra' arguments into an array named after the parameter.❌ Incorrect
In Ruby, `*` in parameters is the 'splat' operator used for variable-length argument lists.QUESTION 2
Given `def show(x, y=10)`, what happens if you call `show(5)`?
An ArgumentError is raised because two arguments are required.
x becomes 5 and y becomes 10.
x becomes 5 and y becomes nil.
The method returns 15 automatically.
✅ Correct!
Since y has a default value of 10, the method proceeds using that default when the second argument is omitted.❌ Incorrect
Default values allow methods to be functional even when the caller provides minimal data.QUESTION 3
What does 'Array Expansion' (Exploding) refer to in a method call?
Converting a string into an array of characters.
Deleting all elements in an array to free memory.
Using `*` before an array to pass its elements as individual arguments.
Expanding the heap to accommodate larger arrays.
✅ Correct!
Using `*arr` in a call 'explodes' the array, filling the method's parameter slots one by one.❌ Incorrect
Expansion refers to satisfying individual parameters using the contents of a single array.QUESTION 4
If a Ruby method has no explicit `return` keyword, what does it return?
It returns nil by default.
It returns true if the code executed successfully.
It returns the value of the last expression evaluated.
It returns the name of the method as a string.
✅ Correct!
Ruby is expression-based; the result of the final line is the implicit return value.❌ Incorrect
Unless interrupted by an explicit `return`, Ruby always passes back the result of the last expression.QUESTION 5
How are multiple return values handled in `return a, b`?
Ruby only returns the first value (a).
Ruby returns an array `[a, b]` which can be destructured.
It results in a syntax error; only one value can be returned.
The values are added together before returning.
✅ Correct!
Ruby packages multiple values into an array, allowing for clean parallel assignment like `x, y = meth()`.❌ Incorrect
Multiple values are conveniently bundled into an array for the caller.Flexible Logging System Case Study
Designing an adaptive interface
You are building a logging system. Usually, you only pass a message. Occasionally, you need to pass a list of error codes. You define the method: `def log(msg='Info', *codes)`. The codes should be joined into a string if present.
Q
If you call `log()`, what are the values of `msg` and `codes` inside the method?
Solution:
`msg` will be 'Info' (the default value) and `codes` will be an empty array `[]`.
`msg` will be 'Info' (the default value) and `codes` will be an empty array `[]`.
Q
If you have an array `errs = [404, 500]`, how do you call `log` so 'Critical' is the message and the errors are captured in the `codes` array?
Solution:
Call it using the splat operator: `log('Critical', *errs)`. This explodes the array into individual arguments after the first one.
Call it using the splat operator: `log('Critical', *errs)`. This explodes the array into individual arguments after the first one.
Q
How does Ruby's expression-based return benefit this logger if the last line is `codes.empty? ? msg : "#{msg}: #{codes.join(', ')}"`?
Solution:
The method automatically returns the formatted string without needing an explicit `return` keyword, making the code more concise and readable.
The method automatically returns the formatted string without needing an explicit `return` keyword, making the code more concise and readable.